<?php

declare(strict_types=1);

namespace app\file\controller\admin;

use think\Request;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use app\file\model\FileGroup as FileGroupModel;
use app\file\model\File as FileModel;

class Group extends Backend
{

    protected function initialize()
    {
        $this->model = new FileGroupModel;
        $this->fileModel = new FileModel;
    }


    /**
     * 分组列表
     *
     * @return void
     */
    public function list()
    {
        $groups = $this->model->order('weigh', 'desc')->select();

        return success('获取成功', $groups);
    }


    /**
     * 添加分组
     *
     * @param Request $request
     * @return void
     */
    public function add(Request $request)
    {
        $params = $request->param();
        $this->svalidate($params, ".add");

        $group = $this->model;
        $group->name = $request->param('name');
        $group->group = $request->param('group');
        $group->save();

        return success('保存成功', $group);
    }


    /**
     * 更新分组名称
     *
     * @param Request $request
     * @return void
     */
    public function edit(Request $request, $id)
    {
        $params = $this->request->only(['name']);
        $this->svalidate($params);

        $this->model->where('id', $id)->save($this->request->post());
        return success('保存成功');
    }


    /**
     * 删除文件分组
     *
     * @return void
     */
    public function delete($id)
    {
        $id = explode(',', $id);
        foreach ($this->model->whereIn('id', $id)->cursor() as $group) {
            $file = $this->fileModel->where('group', $group->group)->count();
            if ($file) {
                throw new SheepException('分组 ' . $group->name . ' 存在文件，请先删除文件');
            } else {
                $group->delete();
            }
        }

        return success('删除成功');
    }
}
